﻿using System;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class DValRecord : BiffRecord
    {
        private uint xLeft;
        private uint yTop;
        private uint idObj;
        private uint idvMac;
        private bool fWnClosed;
        private bool C = true;

        public DValRecord(int count)
        {
            this.idvMac = (uint) count;
            idObj = 0xffffffff;
        }

        public DValRecord()
        {
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            ReadReader(context.Reader);
        }

        private void ReadReader(BinaryReader reader)
        {
#if DEBUG
            ReadWriteChecker.CheckClass((t, r) => t.ReadReader(r), (t, w) => t.WriteWriter(w), reader, this);
#endif

            ushort u = reader.ReadUInt16();
            this.fWnClosed = (u & 0x01) != 0;
            this.C = (u & 0x04) != 0;
            this.xLeft = reader.ReadUInt32();
            this.yTop = reader.ReadUInt32();
            this.idObj = reader.ReadUInt32();
            this.idvMac = reader.ReadUInt32();
        }


        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.DVal; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            WriteWriter(context.Writer);
        }

        private void WriteWriter(BinaryWriter writer)
        {
            ushort u = 0;
            if (fWnClosed)
                u = 1;
            if (C)
                u |= 4;
            writer.Write(u);
            writer.Write(xLeft);
            writer.Write(yTop);
            writer.Write(idObj);
            writer.Write(idvMac);
        }
    }
}